package cn.java79.springboot.zsb.util;

import org.apache.commons.codec.binary.Base64;

import java.text.SimpleDateFormat;
import java.util.Date;

public class StrUtil {
    private StrUtil() {
    }

    private static final SimpleDateFormat DF = new SimpleDateFormat("yyyy-MM-dd");

    //判断s是否是空，包括null和 ""
    public static boolean isBlank(Object s) {
        if (s == null)
            return true;
        else if (s instanceof String) {
            return s.equals("");
        }
        return false;
    }
    public static String trim(Object s) {
        if (s == null)
            return "";
        else if (s instanceof String) {
            return ((String) s).trim();
        }
        return s.toString();
    }
    public static Date toDate(String str) {
        try {
            synchronized (DF) {
                return DF.parse(str);
            }
        } catch (Exception e) {
           // e.printStackTrace();
        }
        return null;
    }

    public static String toStr(Date str) {
        try {
            return DF.format(str);
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return "";
    }
    //去除null
    public static String toStr(String str) {
        if (str == null)
            return "";
        return str;
    }
    //转换成int，转换失败，返回默认值
    public static int toInt(String str,int def) {
        try{
            return Integer.parseInt(str);
        }catch (Exception e){
        }
        return def;
    }
    public static int toInt(String str) {
        return toInt(str,0);
    }
    public static boolean toBoolean(String str) {
        try {
            if("1".equals(str))
                return true;
            return Boolean.parseBoolean(str);
        }catch (Exception e){}
        return false;
    }
    public static long toLong(String str,long def) {
        try{
            return Long.parseLong(str);
        }catch (Exception e){
        }
        return def;
    }
    public static long toLong(String str) {
        try{
            return Long.parseLong(str);
        }catch (Exception e){
        }
        return 0L;
    }
//    private static  BASE64Encoder base64Encoder = new BASE64Encoder();
//    //base64转换
//    public static String toBase64(byte[]b){
//        if(b==null)return "";
//
//        String encode1 = base64Encoder.encode(b);
//        return encode1;
//    }
    //private static  BASE64Encoder base64Encoder = new BASE64Encoder();
    //base64转换
    public static String toBase64(byte[]b){
        if(b==null)return "";
        String encode1 = Base64.encodeBase64String(b);
        return encode1;
    }
}
